<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="menu">
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="handleEdit(scope.row, scope.index)">编 辑</el-button>
        <el-button icon="el-icon-money" size="small" type="text" @click.stop="handleRate(scope.row, scope.index)">结算价设置</el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleSave">新 增</el-button>
        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.aisle_policy_delete"
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
      <template slot-scope="{}" slot="policyNoSearch">
        <select-page
          ref="searchPolSelect"
          label="policyName"
          value="policyNo"
          :select.sync="search.policyNo"
          :url="'rb-core/core/rbpAislePolicy/list'"
          placeholder-text="政策"
          filter-key="policyName"
        ></select-page>
      </template>
      <template slot-scope="{}" slot="aisleCodeSearch">
        <select-page
          ref="searchAisSelect"
          label="aisleName"
          value="aisleCode"
          :select.sync="search.aisleCode"
          :url="'rb-core/core/aisle/rbp_pay_aisle/page'"
          placeholder-text="通道"
          filter-key="aisleName"
        ></select-page>
      </template>
    </avue-crud>
    <el-dialog
      class="el-dialog__wrapper avue-dialog avue-crud__dialog"
      style=""
      :title="dialogText"
      :width="screenWidth>1920?'50%':(screenWidth<=1920 && screenWidth>1500)?'66%':'80%'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <div v-if="dialogType === 'add' || dialogType === 'edit'">
        <platform-policy :policyForm="policyForm" ref="toPolicy" @aisleChange="aisleChange" />
      </div>
      <div v-if="dialogType === 'add' || dialogType === 'rate'">
        <platformPolicyTable ref="myTable"></platformPolicyTable>
      </div>
      <span slot="footer" class="avue-dialog__footer avue-dialog__footer--right">
        <el-button size="small" type="primary" icon="el-icon-circle-plus-outline" v-preventClick @click="policySubmit">保 存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="() => { dialogVisible = false; initEmpty(); }">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
} from "@/api/rb-core/aislePolicy/aisle_policys";
import { template } from "@/api/rb-core/aislePolicy/aisle_policys";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import selectPage from "@/components/select-page/select-page";
import platformPolicy from '@/components/rb-platform/platform-policy-v3';
import platformPolicyTable from '@/components/rb-platform/platform-policy-table';

export default {
  components: {
    selectPage,
    platformPolicy,
    platformPolicyTable
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      screenWidth: document.documentElement.clientWidth,
      loading: true,
      excelBox: false,
      dialogText: '',
      dialogType: '',
      dialogVisible: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        column: [
          {
            label: "政策编号",
            searchLabel: "政策名称",
            prop: "policyNo",
            type: "input",
            search: true,
            display: false,
            minWidth: 110,
            overHidden: true
          },
          {
            label: "政策名称",
            prop: "policyName",
            type: "input",
            display: false,
            minWidth: 130,
            rules: [
              {
                required: true,
                message: "请输入政策名称",
                trigger: "blur",
              },
            ],
            overHidden: true
          },
          {
            label: "通道简称",
            prop: "aisleKindName",
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "通道简称",
            prop: "aisleKind",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=rbp_aisle_kind",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            editDisabled: false,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择通道简称",
                trigger: "blur",
              },
            ],
            display: false,
            overHidden: true,
          },
          {
            label: "通道编号",
            searchLabel: '通道名称',
            prop: "aisleCode",
            type: "select",
            dicUrl: "/api/rb-core/core/aisle/rbp_pay_aisle/page?current=-1&size=-1",
            props: {
              label: "aisleName",
              value: "aisleCode",
            },
            dicFormatter:(data)=>{
              return data.data.records
            },
            search: true,
            hide: true,
            clearable: true,
            dataType: "string",
            minWidth: 110,
            display: false,
            rules: [
              {
                required: true,
                message: "请输入通道编号",
                trigger: "blur",
              },
            ],
            overHidden: true
          },
          {
            label: "通道名称",
            prop: "aisleName",
            display: false,
            minWidth: 130,
            overHidden: true
          },
          {
            label: "通道商编号",
            prop: "aisleCompanyCode",
            searchLabel: '通道商名称',
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=rbp_aisle_company",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            search: true,
            hide: true,
            clearable: true,
            dataType: "string",
            display: false,
            minWidth: 130,
            overHidden: true,
          },
          {
            label: "通道商名称",
            prop: "aisleCompanyName",
            display: false,
            minWidth: 130,
            overHidden: true,
          },
          {
            label: "通道类型",
            prop: "aisleType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=aisle_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            hide: true,
            minWidth: 110,
            display: false,
            rules: [
              {
                required: true,
                message: "请选择通道类型",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "通道类型",
            prop: "aisleTypeName",
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "接入类型",
            prop: "aisleMerchantTypeName",
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "接入类型",
            prop: "aisleMerchantType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=merchant_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            hide: true,
            display: false,
            minWidth: 110,
            rules: [
              {
                required: true,
                message: "请选择接入类型",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "分润类型",
            prop: "profitType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=policy_profit_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            hide: true,
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "分润类型",
            prop: "profitTypeName",
            display: false,
            minWidth: 110,
            overHidden: true
          },
          {
            label: "发放类型",
            prop: "ruleType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=policy_rule_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            hide: true,
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "发放类型",
            prop: "ruleTypeName",
            display: false,
            minWidth: 110,
            overHidden: true
          },
          {
            label: "通道政策状态",
            prop: "policyStatus",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=policy_policy_status",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            hide: true,
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "通道政策状态",
            prop: "policyStatusName",
            display: false,
            overHidden: true,
          },
          {
            label: "交易状态",
            prop: "tradeStatus",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=policy_trade_status",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            hide: true,
            minWidth: 110,
            display: false,
            rules: [
              {
                required: true,
                message: "请选择交易状态",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "交易状态",
            prop: "tradeStatusName",
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "分配状态",
            prop: "allotStatus",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=policy_allot_status",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            hide: true,
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "分配状态",
            prop: "allotStatusName",
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "开户状态",
            prop: "openRpiStatus",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=policy_open_rpi_status",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            search: true,
            hide: true,
            minWidth: 110,
            display: false,
            rules: [
              {
                required: true,
                message: "请选择开户状态",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "开户状态",
            prop: "openRpiStatusName",
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "是否核算分润",
            prop: "isShare",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=policy_is_share",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            hide: true,
            display: false,
            minWidth: 110,
            overHidden: true,
          },
          {
            label: "是否核算分润",
            prop: "isShareName",
            display: false,
            minWidth: 110,
            overHidden: true,
          },
        ],
      },
      data: [],
      policyForm: {
        aisleCode: '',
        policyName: '',
        aisleCompanyName: '',
        aisleKindName: '',
        aisleTypeName: '',
        aisleMerchantTypeName: '',
        profitType: '',
        ruleType: '',
        isShare: 0,
        policyStatus: 1,
        tradeStatus: 1,
        allotStatus: 1,
        openRpiStatus: 1,
      },
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-core/core/aislePolicy/aisle_policy/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.aisle_policy_add, false),
        viewBtn: this.vaildData(this.permission.aisle_policy_view, false),
        delBtn: this.vaildData(this.permission.aisle_policy_delete, false),
        editBtn: this.vaildData(this.permission.aisle_policy_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    policySubmit() {
      switch (this.dialogType) {
        case 'add':
          this.addSubmit();
          break;
        case 'edit':
          this.editSubmit();
          break;
        case 'rate':
          this.rateSubmit();
          break;
        default:
          break;
      }
    },
    addSubmit() {
      this.$refs['toPolicy'].$refs['policyForm'].validate((valid) => {
        if (valid) {
          let newTableJson = JSON.parse(
            JSON.stringify(this.$refs.myTable.newTableData)
          );
          let tableJson = JSON.parse(
            JSON.stringify(this.$refs.myTable.tableData)
          );
          let newTableArr = newTableJson.map(v => {
            v.kindRateList.map(a => {
              a.tradeTypeList.map(b => {
                b.rateList = b.rateList.map(e => {
                  let tableItem = tableJson.find(item => item.tradeTypeCard == e.tradeTypeCard);
                  if (tableItem.rate !== e.rate) {
                    e.rate = tableItem.rate;
                  }
                  if (tableItem.rateMin !== e.rateMin) {
                    e.rateMin = tableItem.rateMin;
                  }
                  if (tableItem.rateMax !== e.rateMax) {
                    e.rateMax = tableItem.rateMax;
                  }
                  if (tableItem.rateScale !== e.rateScale) {
                    e.rateScale = tableItem.rateScale;
                  }
                  return {
                    ...e
                  };
                });
                return {
                  ...b
                };
              });
              return {
                ...a
              };
            });
            return {
              ...v
            };
          });
          let parmas = {
            tradDTO: {
              orderTradList: newTableArr
            },
            ...this.policyForm,
          };
          add(parmas).then(
            () => {
              this.onLoad(this.page);
              this.initEmpty();
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.dialogVisible = false;
            },
            (error) => {
              window.console.log(error);
            }
          );
        }
      });
    },
    editSubmit() {
      this.$refs['toPolicy'].$refs['policyForm'].validate((valid) => {
        if (valid) {
          update(this.policyForm).then(
            () => {
              this.onLoad(this.page);
              this.initEmpty();
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.dialogVisible = false;
            },
            (error) => {
              window.console.log(error);
            }
          );
        }
      });
    },
    rateSubmit() {
      let newTableJson = JSON.parse(
        JSON.stringify(this.$refs.myTable.newTableData)
      );
      let tableJson = JSON.parse(
        JSON.stringify(this.$refs.myTable.tableData)
      );
      let newTableArr = newTableJson.map(v => {
        v.kindRateList.map(a => {
          a.tradeTypeList.map(b => {
            b.rateList = b.rateList.map(e => {
              let tableItem = tableJson.find(item => item.tradeTypeCard == e.tradeTypeCard);
              if (tableItem.rate !== e.rate) {
                e.rate = tableItem.rate;
              }
              if (tableItem.rateMin !== e.rateMin) {
                e.rateMin = tableItem.rateMin;
              }
              if (tableItem.rateMax !== e.rateMax) {
                e.rateMax = tableItem.rateMax;
              }
              if (tableItem.rateScale !== e.rateScale) {
                e.rateScale = tableItem.rateScale;
              }
              return {
                ...e
              };
            });
            return {
              ...b
            };
          });
          return {
            ...a
          };
        });
        return {
          ...v
        };
      });
      let parmas = {
        tradDTO: {
          orderTradList: newTableArr
        },
        id: this.policyForm.id
      };
      update(parmas).then(
        () => {
          this.onLoad(this.page);
          this.initEmpty();
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.dialogVisible = false;
        },
        (error) => {
          window.console.log(error);
        }
      );
    },
    async aisleChange(e) {
      await template(e).then((res) => {
        if (res.data.code == "200") {
          const tableDatas = res.data.data;
          this.$refs.myTable.initTableData('add', tableDatas.orderTradList);
        } else {
          this.$message({
            type: "error",
            message: res.data.message,
          });
        }
      });
    },
    handleSave() {
      this.dialogVisible = true;
      this.dialogType = 'add';
      this.dialogText = "新增政策";
    },
    handleEdit(row, index) {
      this.dialogVisible = true;
      this.dialogType = 'edit';
      this.dialogText = "编辑政策";
      getDetail(row.id).then((res) => {
        this.policyForm = {...this.policyForm, ...res.data.data};
      });
    },
    handleRate(row, index) {
      this.dialogVisible = true;
      this.dialogType = 'rate';
      this.dialogText = "结算价设置";
      getDetail(row.id).then((res) => {
        if (res.data.code == "200") {
          const data = res.data.data;
          this.policyForm = {...this.policyForm, 'id': res.data.data.id};
          this.$refs.myTable.initTableData('edit', data.tradDTO.orderTradList);
        } else {
          this.$message({
            type: "error",
            message: res.data.message,
          });
        }
      });
    },
    handleClose(done) {
      this.initEmpty();
      done()
    },
    initEmpty() {
      switch (this.dialogType) {
        case 'add':
          this.$refs['toPolicy'].$refs['policyForm'].resetFields();
          this.policyForm = {
            aisleCode: '',
            policyNo: '',
            policyName: '',
            aisleCompanyName: '',
            aisleKindName: '',
            aisleTypeName: '',
            aisleMerchantTypeName: '',
            profitType: '',
            ruleType: '',
            isShare: 0,
            policyStatus: 1,
            tradeStatus: 1,
            allotStatus: 1,
            openRpiStatus: 1,
          };
          this.$refs.myTable.tableData = [];
          break;
        case 'edit':
          this.$refs['toPolicy'].$refs['policyForm'].resetFields();
          this.policyForm = {
            aisleCode: '',
            policyNo: '',
            policyName: '',
            aisleCompanyName: '',
            aisleKindName: '',
            aisleTypeName: '',
            aisleMerchantTypeName: '',
            profitType: '',
            ruleType: '',
            isShare: 0,
            policyStatus: 1,
            tradeStatus: 1,
            allotStatus: 1,
            openRpiStatus: 1,
          };
          break;
        case 'rate':
          this.$refs.myTable.tableData = [];
          break;
        default:
          break;
      }
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&policyNo=${this.search.policyNo}`;
      exQuery += `&policyName=${this.search.policyName}`;
      exQuery += `&polTypeCode=${this.search.polTypeCode}`;
      exQuery += `&aisleCode=${this.search.aisleCode}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-core/core/aislePolicy/aisle_policy/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-core/core/aislePolicy/aisle_policy/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>

</style>
